package com.zygh.lz.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.dao.*;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.remould.Assess;
import com.zygh.lz.entity.remould.Xareas;
import com.zygh.lz.service.BrigadeRecordService;
import com.zygh.lz.util.DataTime;
import com.zygh.lz.util.DistanceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 大队档案统计
 *
 * @author wxh
 */
@Slf4j
@Service
public class BrigadeRecordServiceImpl implements BrigadeRecordService {
    @Resource
    private BrigadeRecordMapper brigadeRecordMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private InformationMapper informationMapper;
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private IllegalDataMapper illegalDataMapper;
    @Resource
    private IllegalMapper illegalMapper;

    @Resource
    private EfficiencyMapper efficiencyMapper;
    @Resource
    private EfficiencyRateMapper efficiencyRateMapper;
    @Resource
    private DutyrosterMapper dutyrosterMapper;
    @Resource
    private SignMapper signMapper;

    @Resource
    private GpsServiceImpl gpsService;
    @Resource
    private GpsMapper gpsMapper;

    @Resource
    private StaffMapper staffMapper;
    @Resource
    private PoliceDataMapper policeDataMapper;
    @Resource
    private ProblemMapper problemMapper;
    @Resource
    private ProblemtypeMapper problemtypeMapper;
    @Resource
    private CalendarsMapper calendarsMapper;
    @Resource
    private EquipageMapper equipageMapper;

    @Value("${max-depth}")
    private Integer maxDepth;

    //分数阈值
    private static int totalDistanceGrade = 100;
    private static int durationsGrade = 30;
    private static int livenessGrade = 50;
    private static int illegalDataGrade = 10;

    /**
     * 获取总巡逻时长
     *
     * @param sectionId 部门id
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 总巡逻时长
     */
    @Override
    public List<Map> getTotalPatrolDuration(Integer sectionId, String startTime, String endTime) throws ParseException {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        List startEnd = com.zygh.lz.util.DateUtil.getStartEnd(startTime, endTime);
        String[] week = new String[startEnd.size()];
        Integer[] num = new Integer[startEnd.size()];
        for (int i = 0; i < startEnd.size(); i++) {
            Map<String, String> time = SignServiceImpl.getTime(startEnd.get(i).toString());
            //一天的巡逻时长
            Integer totalPatrolDuration = brigadeRecordMapper.getTotalPatrolDuration(sectionId, time.get("startTime"), time.get("endTime"));
            week[i] = startEnd.get(i).toString();
            num[i] = totalPatrolDuration;
        }
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        map.put("week", week);
        map.put("totalPatrolDuration", num);
        list.add(map);
        return list;
    }

    /**
     * 获取总空岗数量
     *
     * @param sectionId 部门id
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 总空岗数量
     */
    @Override
    public Integer getTotalVacantPost(Integer sectionId, String startTime, String endTime) {
        return brigadeRecordMapper.getTotalVacantPost(sectionId, startTime + " 00:00:00", endTime + " 23:59:59");
    }

    /**
     * 获取签到统计
     *
     * @param sectionId 部门id
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 签到统计
     */
    @Override
    public List<Map<String, Object>> getSignStatistics(Integer sectionId, String startTime, String endTime) {
        //判断是查询单天还是多天，如果是单天则按小时查，如果是多天则按天查
        if (!startTime.equals(endTime)) {
            //获取统计结果，例：[{"count":125,"time":"2022-01-13"},{"count":16,"time":"2022-01-17"},{"count":6,"time":"2022-01-18"}]
            return brigadeRecordMapper.getSignStatistics(sectionId, startTime + " 00:00:00", endTime + " 23:59:59");
        } else {
            //如果是今天则获取到当前小时
            if (DateTime.now().toString("yyyy-MM-dd").equals(startTime)) {
                //获取统计结果，例：[{"count":125,"time":"01"},{"count":16,"time":"02"},{"count":6,"time":"03"}]
                return brigadeRecordMapper.getSignStatisticsByHour(sectionId, startTime + " 00:00:00", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
            } else {
                //获取统计结果，例：[{"count":125,"time":"01"},{"count":16,"time":"02"},{"count":6,"time":"03"}]
                return brigadeRecordMapper.getSignStatisticsByHour(sectionId, startTime + " 00:00:00", endTime + " 23:59:59");
            }
        }
    }

    @Override
    public List<Map<String, Object>> getSignWeek(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认一天
            startTime = DataTime.getStartDate();
            //startTime = DataTime.getStartDay();
            endTime = DataTime.getEndDay();
        }
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                sectionId = null;
            }
        }

        List<Map<String, Object>> mapList = calendarsMapper.findCalendarByTime(startTime, endTime);
        for (Map map : mapList) {
            //民警签到人数
            map.put("signInNum", brigadeRecordMapper.getSignedByTime(sectionId,
                    DateUtil.beginOfDay(DateUtil.parse(map.get("datelist").toString())).toString(),
                    DateUtil.endOfDay(DateUtil.parse(map.get("datelist").toString())).toString(), "民警"));
            //辅警签到人数
            map.put("auxiliary", brigadeRecordMapper.getSignedByTime(sectionId, DateUtil.beginOfDay(DateUtil.parse(map.get("datelist").toString())).toString()
                    , DateUtil.endOfDay(DateUtil.parse(map.get("datelist").toString())).toString(), "辅警"));
            //活跃度
//            List<Map<String, Object>> activityOfDadui = brigadeRecordMapper.getActivityOfDadui( sectionId, DateUtil.beginOfDay(DateUtil.parse(map.get("datelist").toString())).toString(),
//                    DateUtil.endOfDay(DateUtil.parse(map.get("datelist").toString())).toString());
            int findactivity = gpsMapper.findactivity(sectionId, DateUtil.beginOfDay(DateUtil.parse(map.get("datelist").toString())).toString()
                    , DateUtil.endOfDay(DateUtil.parse(map.get("datelist").toString())).toString());
            //map.put("activity", activityOfDadui.get(0).get("rate"));
            map.put("activity", findactivity);
        }
        return mapList;
    }

    /**
     * 获取大队排名
     *
     * @param sectionId 部门id
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 大队排名
     */
    @Override
    public List<Map<String, Object>> getBrigadeRanking(Integer sectionId, String startTime, String endTime) {
        //判断是支队还是大队
        if (sectionId == 74) {
            //支队
            return brigadeRecordMapper.getBrigadeRankingOfMilitiaDetachment(sectionId, startTime + " 00:00:00", endTime + " 23:59:59");
        } else {
            //大队
            return brigadeRecordMapper.getBrigadeRankingOfBrigade(sectionId, startTime + " 00:00:00", endTime + " 23:59:59");
        }
    }

    /**
     * 获取总巡查里程与签到趋势
     *
     * @param sectionId 部门id
     * @param startTime 统计开始时间
     * @param endTime   统计结束时间
     * @return 总巡查里程与签到趋势
     */
    @Override
    public List<Map<String, Object>> getMileageAndSignTrend(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                sectionId = null;
            }
        }
        return brigadeRecordMapper.getMileageAndSignTrend(sectionId, startTime, endTime);
    }


    @Override
    public List<Map> positionOf(String sectionId) {
        //大队下岗位类型
        List<Map> station = xareaMapper.findStation(sectionId);
        for (Map map : station) {
            //民警和辅警数量
            Xareas xareas = new Xareas();
            xareas.setStation(map.get("station").toString())
                    .setSectionDid(Integer.valueOf(map.get("section_Did").toString()))
                    .setStaffType("民警");
            //民警警力数
            int policeStrength = xareaMapper.findPoliceStrength(xareas);
            map.put("policeNum", policeStrength);
            xareas.setStaffType("辅警");
            int policeStrength1 = xareaMapper.findPoliceStrength(xareas);
            map.put("auxiliary", policeStrength1);
        }
        return station;
    }

    @Override
    public List<Map> informationInfo(Integer sectionId) {
        //待处理警情

        //调度信息
        return informationMapper.findInformationInfo(sectionId);

    }

    @Override
    public List<Map<String, Object>> illegalData(Integer sectionId, Integer sysStaffId, String startTime, String endTime, Integer depthNumber) {
        depthNumber++;
        //执法信息 默认取当天
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            String sectionName = section.getSectionName();
            dui = sectionName.substring(0, sectionName.indexOf("队") + 1);
            //dui = dui.replace("支", "大");
        }
        List<Map<String, Object>> data = new ArrayList<>();
//        List<Map<String, Object>> illegalType = illegalDataMapper.findIllegalType(DataTime.getStartTheDay(), DataTime.getEndDate(), dui);

        //List<Map<String, Object>> illegalData = illegalDataMapper.findIllegalData(DataTime.getStartTheDay(), DataTime.getEndDate(), dui);
        List<Illegal> illegalList = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                .eq(Illegal::getSysStaffId, sysStaffId));
        if (illegalList == null || illegalList.size() == 0) {
            illegalList = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                    .groupBy(Illegal::getIllegalCode));
        }
        for (Illegal illegal : illegalList) {
            int wfCount = 1;
            wfCount = illegal.getNum() == null ? 1 : illegal.getNum();
            List<Map<String, Object>> illegalData = illegalDataMapper.findIllegalDataByType(startTime, endTime, dui, illegal.getIllegalCode(), wfCount);
            data.addAll(illegalData);
        }
//        for (Map<String, Object> stringObjectMap : illegalType) {
//            Illegal wfxw = illegalMapper.selectOne(Wrappers.<Illegal>lambdaQuery()
//                    .eq(Illegal::getSysStaffId, sysStaffId)
//                    .eq(Illegal::getIllegalCode, stringObjectMap.get("wfxw").toString()));
//            int wfCount = 1;
//            if (Objects.nonNull(wfxw)) {
//                wfCount = wfxw.getNum() == null ? 1 : wfxw.getNum();
//            }
//            List<Map<String, Object>> illegalData = illegalDataMapper.findIllegalDataByType(DataTime.getStartTheDay(), DataTime.getEndDate(), dui, stringObjectMap.get("wfxw").toString(), wfCount);
//            data.addAll(illegalData);
//        }
        data = data.stream().sorted((o1, o2) -> {
            String time1 = o1.get("wfsj").toString();
            String time2 = o2.get("wfsj").toString();

            DateTime date1 = DateUtil.parse(time1);
            DateTime date2 = DateUtil.parse(time2);
            long between = DateUtil.between(date1, date2, DateUnit.SECOND, false);
            return Integer.valueOf((int) between);
        }).collect(Collectors.toList());

        if (data.size() < 10 && depthNumber <= maxDepth) {
            String start = DateUtil.offsetDay(DateUtil.parse(startTime), -1).toString();
            String end = DateUtil.offsetDay(DateUtil.parse(endTime), -1).toString();
            return illegalData(sectionId, sysStaffId, start, end, depthNumber);
        }

//        if (data.size() < 10) {
//            List<Map<String, Object>> yesterData = new ArrayList<>(10);
//            List<Illegal> illegalLists = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
//                    .eq(Illegal::getSysStaffId, sysStaffId));
//            for (Illegal illegal : illegalLists) {
//                int wfCount = 1;
//                wfCount = illegal.getNum() == null ? 1 : illegal.getNum();
//                List<Map<String, Object>> illegalData = illegalDataMapper.findIllegalDataByType(DataTime.getStartDay(), DataTime.getEndDate(), dui, illegal.getIllegalCode(), wfCount);
//                yesterData.addAll(illegalData);
//            }
////            List<Map<String, Object>> yesterDayIllegalType = illegalDataMapper.findIllegalType(DataTime.getStartDay(), DataTime.getEndDate(), dui);
////            for (Map<String, Object> stringObjectMap : yesterDayIllegalType) {
////                int wfCount = 1;
////                Illegal wfxw = illegalMapper.selectOne(Wrappers.<Illegal>lambdaQuery()
////                        .eq(Illegal::getSysStaffId, sysStaffId)
////                        .eq(Illegal::getIllegalCode, stringObjectMap.get("wfxw").toString()));
////                if (Objects.nonNull(wfxw)) {
////                    wfCount = wfxw.getNum() == null ? 1 : wfxw.getNum();
////                }
////
////
////                List<Map<String, Object>> illegalData = illegalDataMapper.findIllegalDataByType(DataTime.getStartDay(), DataTime.getEndDate(), dui, stringObjectMap.get("wfxw").toString(), wfCount);
////                yesterData.addAll(illegalData);
////            }
//            yesterData = yesterData.stream().sorted((o1, o2) -> {
//                String time1 = o1.get("wfsj").toString();
//                String time2 = o2.get("wfsj").toString();
//
//                DateTime date1 = DateUtil.parse(time1);
//                DateTime date2 = DateUtil.parse(time2);
//                long between = DateUtil.between(date1, date2, DateUnit.SECOND, false);
//                return Integer.valueOf((int) between);
//            }).collect(Collectors.toList());
//            return yesterData;
//        }
        return data;
    }


    @Override
    public Map illegalDataNum(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认当天
            startTime = DataTime.getStartTheDay();
            endTime = DataTime.getEndDate();
        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                dui = null;
            } else {
                String sectionName = section.getSectionName();
                dui = sectionName.substring(0, sectionName.indexOf("队") + 1);
                //dui = dui.replace("支", "大");
            }


        }
        Map<String, Object> map = new HashMap<>();

//        Integer integer = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
//                .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
//                .between(IllegalData::getWfsj, startTime, endTime));
//        map.put("illegalSum", integer);
//        if (integer < 1) {
//            map.put("illegalSum", illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
//                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
//                    .between(IllegalData::getWfsj, DataTime.getStartDay(), endTime)));
//        }


        Integer xc = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                .between(IllegalData::getWfsj, startTime, endTime)
                .eq(IllegalData::getType, 1));
        map.put("sceneNum", xc);
        if (xc < 1) {
            map.put("sceneNum", illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .between(IllegalData::getWfsj, DataTime.getStartDay(), endTime)
                    .eq(IllegalData::getType, 1)));
        }

        Integer fxc = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                .between(IllegalData::getWfsj, startTime, endTime)
                .eq(IllegalData::getType, 2));
        map.put("offSceneNum", fxc);
        if (fxc < 1) {
            map.put("offSceneNum", illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .between(IllegalData::getWfsj, DataTime.getStartDay(), endTime)
                    .eq(IllegalData::getType, 2)));
        }
        Integer sceneNum = Integer.valueOf(map.get("sceneNum").toString());
        Integer offSceneNum = Integer.valueOf(map.get("offSceneNum").toString());

        map.put("illegalSum", sceneNum + offSceneNum);
        return map;
    }

    @Override
    public Map<String, Object> alertInfo(Integer id) {
        //默认取一周的数据
        String startTime = DataTime.getStartDate();
        String endTime = DataTime.getEndDate();

        Staff staff = staffMapper.selectByPrimaryKey(id);
        //个人排名
        List<Map<String, Object>> illegalDateRanking = policeDataMapper.findPoliceDateRanking(staff.getStaffNum(), startTime, endTime);
        //前三名
        List<Map<String, Object>> illegalDateRankings = policeDataMapper.findPoliceDateTop3(startTime, endTime);
        List<Map<String, Object>> merge = DistanceUtil.merge(illegalDateRanking, illegalDateRankings);
        Map<String, Object> map = new HashMap<>();
        map.put("ranking", merge);
        return map;

    }


    /**
     * 获取顶部信息
     *
     * @param sectionId 部门id
     * @return 顶部信息
     */
    @Override
    public List<Map<String, Object>> getTopChange(Integer sectionId) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 获取今天和昨天日期
        //String today = DateTime.now().toString("yyyy-MM-dd");
        //String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        String today = "2020-06-30";
        String yesterday = "2020-06-29";

        // 获取民警今天和昨天签到数量
        Integer todayMjSignedNum = brigadeRecordMapper.getSignedByTime(sectionId, today + " 00:00:00", today + " 23:59:59", "民警");
        Integer yesterdayMjSignedNum = brigadeRecordMapper.getSignedByTime(sectionId, yesterday + " 00:00:00", yesterday + " 23:59:59", "民警");
        //计算民警签到量变化率
        Integer signedMjChange = yesterdayMjSignedNum != 0 ? Integer.valueOf(String.format("%.0f", (double) (todayMjSignedNum - yesterdayMjSignedNum) * 100 / yesterdayMjSignedNum)) : 0;
        HashMap<String, Object> signedNumMapMj = new HashMap<>(2);
        signedNumMapMj.put("signedMj", todayMjSignedNum);
        signedNumMapMj.put("signedChangeMj", signedMjChange);
        mapList.add(signedNumMapMj);

        // 获取辅警今天和昨天签到数量
        Integer todayFjSignedNum = brigadeRecordMapper.getSignedByTime(sectionId, today + " 00:00:00", today + " 23:59:59", "辅警");
        Integer yesterdayFjSignedNum = brigadeRecordMapper.getSignedByTime(sectionId, yesterday + " 00:00:00", yesterday + " 23:59:59", "辅警");
        //计算民警签到量变化率
        Integer signedFjChange = yesterdayFjSignedNum != 0 ?
                Integer.valueOf(String.format("%.0f", (double) (todayFjSignedNum - yesterdayFjSignedNum) * 100 / yesterdayFjSignedNum)) : 0;
        HashMap<String, Object> signedNumMapFj = new HashMap<>(2);
        signedNumMapFj.put("signedFj", todayFjSignedNum);
        signedNumMapFj.put("signedChangeFj", signedFjChange);
        mapList.add(signedNumMapFj);

        // 获取巡逻里程
        Integer todayPatrolDistance = brigadeRecordMapper.getPatrolDistance(sectionId, today + " 00:00:00", today + " 23:59:59");
        Integer yesterdayPatrolDistance = brigadeRecordMapper.getPatrolDistance(sectionId, yesterday + " 00:00:00", yesterday + " 23:59:59");
        //计算巡逻里程变化率
        Integer patrolDistanceChange = yesterdayPatrolDistance != 0 ?
                Integer.valueOf(String.format("%.0f", (double) (todayPatrolDistance - yesterdayPatrolDistance) * 100 / yesterdayPatrolDistance)) : 0;
        HashMap<String, Object> patrolDistanceMap = new HashMap<>(2);
        patrolDistanceMap.put("patrolDistance", todayPatrolDistance);
        patrolDistanceMap.put("patrolDistanceChange", patrolDistanceChange);
        mapList.add(patrolDistanceMap);

        // 获取巡逻总时长
        Integer todayPatrolDuration = brigadeRecordMapper.getTotalPatrolDuration(sectionId, today + " 00:00:00", today + " 23:59:59");
        Integer yesterdayPatrolDuration = brigadeRecordMapper.getTotalPatrolDuration(sectionId, yesterday + " 00:00:00", yesterday + " 23:59:59");
        //计算巡逻总时长变化率
        Integer patrolDurationChange = yesterdayPatrolDuration != 0 ?
                Integer.valueOf(String.format("%.0f", (double) (todayPatrolDuration - yesterdayPatrolDuration) * 100 / yesterdayPatrolDuration)) : 0;
        HashMap<String, Object> patrolDurationMap = new HashMap<>(2);
        patrolDurationMap.put("patrolDuration", todayPatrolDuration);
        patrolDurationMap.put("patrolDurationChange", patrolDurationChange);
        mapList.add(patrolDurationMap);
        return mapList;
    }

    @Override
    public Map efficiency(Integer id) {
        //默认取前一天内的数据
        String startDate = DataTime.getStartDay();
        String endDate = DataTime.getEndDate();

        //计算分数前一天分数
        Efficiency efficiency = efficiencyMapper.selectOne(Wrappers.<Efficiency>lambdaQuery()
                .eq(Efficiency::getStaffId, id).between(Efficiency::getBelongTime, startDate, endDate));
        EfficiencyRate efficiencyRate = efficiencyRateMapper.selectOne(Wrappers.<EfficiencyRate>lambdaQuery().eq(EfficiencyRate::getId, 1));
        if (efficiency == null) {
            return null;
        }
        int distanceGrade = efficiency.getTotalDistanceGrade();
        int durationGrade = efficiency.getDurationGrade();
        int liveneGrade = efficiency.getLivenessGrade();
        int illegalGrade = efficiency.getIllegalDataGrade();
        int jieChujingGrade = efficiency.getJieChujingGrade();
        int problemGrade = efficiency.getProblemGrade();

        //平均数  本大队昨天平均分

        //接处警。。。。

        int totalGrade = distanceGrade + durationGrade + liveneGrade + illegalGrade + jieChujingGrade + problemGrade;

        //集合一周内的各个数值
        Map<String, Object> map = new HashMap<>();
        Assess assess = new Assess();
        assess.setTotalDistance(distanceGrade * efficiencyRate.getMileageRate())
                .setDuration(durationGrade * efficiencyRate.getDurationRate() + 10)
                .setLiveness(liveneGrade * efficiencyRate.getLivenessRate())
                .setIllegalData(illegalGrade * efficiencyRate.getIllegalDataRate())
                .setJieChujing(jieChujingGrade * efficiencyRate.getJieChujingRate());
        map.put("efficacy", assess);
        Map map3 = staffMapper.selectStaffInfoById(id);
        Assess assess1 = new Assess();
        Map mean = efficiencyMapper.findMean("total_distance_grade", Integer.parseInt(map3.get("section_pid").toString()), startDate, endDate);
        Map mean1 = efficiencyMapper.findMean("duration_grade", Integer.parseInt(map3.get("section_pid").toString()), startDate, endDate);
        Map mean2 = efficiencyMapper.findMean("liveness_grade", Integer.parseInt(map3.get("section_pid").toString()), startDate, endDate);
        Map mean3 = efficiencyMapper.findMean("illegal_data_grade", Integer.parseInt(map3.get("section_pid").toString()), startDate, endDate);
        Map mean4 = efficiencyMapper.findMean("Jie_chuJing_grade", Integer.parseInt(map3.get("section_pid").toString()), startDate, endDate);
        assess1.setTotalDistance(Integer.valueOf(mean.get("avgNum").toString()) / Integer.valueOf(mean.get("count").toString()) * efficiencyRate.getMileageRate())
                .setDuration(Integer.valueOf(mean1.get("avgNum").toString()) / Integer.valueOf(mean1.get("count").toString()) * efficiencyRate.getDurationRate())
                .setLiveness(Integer.valueOf(mean2.get("avgNum").toString()) / Integer.valueOf(mean2.get("count").toString()) * efficiencyRate.getLivenessRate())
                .setIllegalData(Integer.valueOf(mean3.get("avgNum").toString()) / Integer.valueOf(mean3.get("count").toString()) * efficiencyRate.getIllegalDataRate())
                .setJieChujing(Integer.valueOf(mean4.get("avgNum").toString()) / Integer.valueOf(mean4.get("count").toString()) * efficiencyRate.getJieChujingRate());


        map.put("mean", assess1);
        map.put("totalGrademean", totalGrade);
        return map;


    }

    @Override
    public void efficiencyData(String startTime, String endTime) {
        /**
         * ===================================每天数据量===================================
         */
//        List<Dutyroster> dutyrosters = dutyrosterMapper.selectList(Wrappers.<Dutyroster>lambdaQuery()
////                .isNotNull(Dutyroster::getAssignmentid));

        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            startTime = DateUtil.offsetDay(DateUtil.beginOfDay(new Date()), -1).toString();
            endTime = DateUtil.offsetDay(DateUtil.endOfDay(new Date()), -1).toString();

        }
        //只统计该时间内签到的警员
        List<Sign> signs = signMapper.selectList(Wrappers.<Sign>lambdaQuery()
                .between(Sign::getSignintime, startTime, endTime)
                .groupBy(Sign::getWarningsignal));
        for (Sign sign : signs) {

            Staff staff = staffMapper.selectStaffByNum(sign.getWarningsignal());
            //取前一天的数据
            Map gpsStatistics = gpsService.findGpsStatistics(staff.getSysStaffId(), startTime, endTime);

            //巡查里程
            String totalDistance = gpsStatistics.get("totalDistance").toString();
            //工作时长
            String workHour = gpsStatistics.get("duration").toString();
            //小时
            String duration = workHour.substring(0, workHour.indexOf("小时")).trim();
            //分钟
            String minute = workHour.substring(workHour.indexOf("时") + 1, workHour.indexOf("分")).trim();
            //转分钟
            String time = String.valueOf(Integer.parseInt(duration) * 60 + Integer.parseInt(minute));

            //活跃度
            String liveness = gpsStatistics.get("liveness").toString();

            //执法数据
            List<IllegalData> illegalData = illegalDataMapper.selectList(Wrappers.<IllegalData>lambdaQuery()
                    .eq(IllegalData::getWarningSignal, staff.getStaffNum())
                    .between(IllegalData::getCondition, startTime, endTime));

            //接处警.....
            Integer integer = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                    .eq(PoliceData::getCzhr, staff.getStaffNum())
                    .between(PoliceData::getJjsj01, startTime, endTime));

            //信息上报（额外加分项）
            Integer integer1 = problemMapper.selectCount(Wrappers.<Problem>lambdaQuery()
                    .eq(Problem::getSysStaffId, staff.getSysStaffId())
                    .between(Problem::getProblemDate, startTime, endTime));

            /**
             * =================================计算分数====================================
             */

            //计算分数
            int distanceGrade;
            int durationGrade;
            int liveneGrade;
            int illegalGrade;
            int problemGrade;

            EfficiencyRate efficiencyRate = efficiencyRateMapper.selectOne(Wrappers.<EfficiencyRate>lambdaQuery()
                    .eq(EfficiencyRate::getId, 1));
            //总里程
            double s = Double.valueOf(totalDistance) * 1000;
            if ((int) s >= efficiencyRate.getMileageThreshold()) {
                distanceGrade = 5 + calculateScore((int) s, efficiencyRate.getMileageThreshold());
            } else {
                distanceGrade = 3;
            }
            //总时长

            if (Integer.parseInt(time) >= efficiencyRate.getDurationThreshold()) {
                durationGrade = 25 + calculateScore(Integer.parseInt(time), efficiencyRate.getDurationThreshold());
            } else {
                durationGrade = 20;
            }

            //活跃度
            if (Double.valueOf(liveness).intValue() >= efficiencyRate.getLivenessThreshold()) {
                liveneGrade = 5 + calculateScore(Double.valueOf(liveness).intValue(), efficiencyRate.getLivenessThreshold());
            } else {
                liveneGrade = 3;
            }
            //违法数据
            if (illegalData.size() >= efficiencyRate.getIllegalDataThreshold()) {
                illegalGrade = 15 + calculateScore(illegalData.size(), efficiencyRate.getIllegalDataThreshold());
            } else {
                illegalGrade = 10;
            }

            //接处警。。。。

            //信息上报
            problemGrade = integer1 >= 5 ? 10 : integer1 * 2;

            Efficiency efficiency = new Efficiency();
            efficiency.setCreatTime(new Date())
                    .setTotalDistance(String.valueOf(Double.valueOf(totalDistance) * 1000))
                    .setDuration(time)
                    .setLiveness(liveness)
                    .setIllegalData(illegalData.size())
                    .setJieChujing("0")
                    .setWarningsignal(sign.getWarningsignal())
                    .setStaffId(staff.getSysStaffId())
                    .setBelongTime(DateUtil.parse(startTime))
                    .setTotalDistanceGrade(distanceGrade)
                    .setDurationGrade(durationGrade)
                    .setLivenessGrade(liveneGrade)
                    .setIllegalDataGrade(illegalGrade).setJieChujingGrade(15)
                    .setProblemGrade(problemGrade);

            //巡查里程和在线时长不为0
            if (s != 0 && Integer.parseInt(efficiency.getDuration()) != 0) {
                efficiencyMapper.insertIgnoreNull(efficiency);
            }

        }
    }


    /**
     * 计算应加分数
     *
     * @param grad      实际得分
     * @param threshold 事项阈值
     * @return
     */
    private int calculateScore(int grad, int threshold) {
        int num = grad - threshold;
        if (num > 0) {
            //超过30%最高加5分
            int i = num / threshold;
            if (i < 0.3) {
                return i;
            }
            return 5;
        } else {
            return 0;
        }
    }


    @Override
    public Map getPoliceData(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认当天
            startTime = DataTime.getStartTheDay();
            //startTime = DataTime.getStartMonth();
            endTime = DataTime.getEndDate();
        }
        Map<String, Object> map = new HashMap<>();
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            boolean flse = true;
            int i = 0;
            do {
                i++;
                if (i > 8 || section.getSectionPid() == 74) {
                    flse = false;
                } else {
                    section = sectionMapper.selectByPrimaryKey(section.getSectionPid());
                }
            } while (flse);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                dui = null;
            } else {
                dui = section.getTempid();
            }
        }
        //接处警总数
        Integer integer = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                .like(StringUtils.isNotEmpty(dui), PoliceData::getJjdw, dui)
                .between(PoliceData::getJjsj01, startTime, endTime));
        //已处警情
        Integer integer1 = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(dui), PoliceData::getJjdw, dui)
                .between(PoliceData::getJjsj01, startTime, endTime)
                .eq(PoliceData::getCjbs, 2));
        //事故警情
        Integer acciden = policeDataMapper.accident(dui, startTime, endTime, "事故");
        //秩序警情
        Integer order = policeDataMapper.accident(dui, startTime, endTime, "秩序");

        //亡人事故
        Integer outlaw = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                .between(PoliceData::getJjsj01, startTime, endTime)
                .like(PoliceData::getCjxq, "亡人事故"));

        map.put("jieChuJing", integer);
        map.put("processedJieChu", integer1);
        map.put("acciden", acciden);
        map.put("order", order);

        return map;
    }


    @Override
    public List<Map> getJieChuJing(Integer sectionId, String startTime, String endTime, Integer depNumber) {
        depNumber++;
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认当天
            startTime = DataTime.getStartTheDay();
            endTime = DataTime.getEndDate();
        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            boolean flse = true;
            int i = 0;
            do {
                i++;
                if (i > 5 || section.getSectionPid() == 74) {
                    flse = false;
                } else {
                    section = sectionMapper.selectByPrimaryKey(section.getSectionPid());
                }
            } while (flse);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                dui = null;
            } else {
                dui = section.getTempid();
            }
        }
        List<Map> policeData = policeDataMapper.findPoliceData(dui, startTime, endTime);
        if (policeData.size() < 1 && depNumber <= maxDepth) {
            //如果当日没数据向前寻找直到找到数据为止返回
//            String startDay = DataTime.getStartDay();
            String start = DateUtil.offsetDay(DateUtil.parse(startTime), -1).toString();
            String end = DateUtil.offsetDay(DateUtil.parse(endTime), -1).toString();
            return getJieChuJing(sectionId, start, end, depNumber);
        }
        return policeData;
    }


    @Override
    public List<Map<String, Object>> getWeekJieChuJing(Integer sectionId, String startTime, String endTime) throws ParseException {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();

        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            boolean flse = true;
            int i = 0;
            do {
                i++;
                if (i > 4 || section.getSectionPid() == 74) {
                    flse = false;
                } else {
                    section = sectionMapper.selectByPrimaryKey(section.getSectionPid());
                }
            } while (flse);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                dui = null;
            } else {
                dui = section.getTempid();
            }
        }
        //去时间段内的每天日期
        List startEnd = com.zygh.lz.util.DateUtil.getStartEnd(startTime, endTime);
        String[] week = new String[startEnd.size()];
        Integer[] num = new Integer[startEnd.size()];
        for (int i = 0; i < startEnd.size(); i++) {
            Map<String, String> time = SignServiceImpl.getTime(startEnd.get(i).toString());
            //一天的接处警数
            Integer integer = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                    .eq(StringUtils.isNotEmpty(dui), PoliceData::getCzhdw, dui)
                    .between(PoliceData::getJjsj01, time.get("startTime"), time.get("endTime")));
            week[i] = startEnd.get(i).toString();
            num[i] = integer;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("week", week);
        map.put("policeNum", num);
        list.add(map);
        return list;

    }

    @Override
    public List<Map> getWeekillegallyPark(Integer sectionId, String startTime, String endTime) throws ParseException {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                dui = null;
            } else {
                dui = section.getSectionName().replace("支", "大");
            }
        }
        //去时间段内的每天日期
        List startEnd = com.zygh.lz.util.DateUtil.getStartEnd(startTime, endTime);
        String[] weeks = new String[startEnd.size()];
        Integer[] num = new Integer[startEnd.size()];
        //支
        Integer[] scene = new Integer[startEnd.size()];
        //非现场
        Integer[] offSite = new Integer[startEnd.size()];

        for (int i = 0; i < startEnd.size(); i++) {
            Map<String, String> time = SignServiceImpl.getTime(startEnd.get(i).toString());
            Integer integer = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .between(IllegalData::getWfsj, time.get("startTime"), time.get("endTime")));
            Integer scene1 = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .between(IllegalData::getWfsj, time.get("startTime"), time.get("endTime"))
                    .eq(IllegalData::getType, 1));
            Integer offSite1 = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .between(IllegalData::getWfsj, time.get("startTime"), time.get("endTime"))
                    .eq(IllegalData::getType, 2));


            weeks[i] = startEnd.get(i).toString();
            num[i] = integer;
            scene[i] = scene1;
            offSite[i] = offSite1;
        }
        List<Map> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("week", weeks);
        map.put("policeNum", num);
        map.put("scene", scene);
        map.put("offSite", offSite);
        list.add(map);
        return list;

    }

    @Override
    public Map getWeekInformation(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                sectionId = null;
            }
        }
        Map<String, Object> map = new HashMap<>();

        map.put("informationSum", informationMapper.findInformationStatis(sectionId, startTime, endTime, null, null));
        map.put("isReadNum", informationMapper.findInformationStatis(sectionId, startTime, endTime, 1, null));
        map.put("staple", informationMapper.findInformationStatis(sectionId, startTime, endTime, null, "staple"));
        map.put("importent", informationMapper.findInformationStatis(sectionId, startTime, endTime, null, "importent"));
        map.put("urgency", informationMapper.findInformationStatis(sectionId, startTime, endTime, null, "urgency"));

        return map;
    }

    @Override
    public List<Map> focusOnIllegal(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            dui = section.getSectionName().substring(0, section.getSectionName().indexOf("队") + 1);
            //dui = dui.replace("支", "大");
        }

        List<Map> mapList = new ArrayList<>();
        //获取不同类型的违法代码
        String[] xtype = new String[]{"闯红灯", "闯禁行", "无证驾驶", "工程运输车"};
        String[] dtype = new String[]{"涉牌涉证", "三超一疲劳", "酒驾毒驾"};

        for (String s : xtype) {
            Map<String, Object> map = new HashMap<>();
            //获取违法代码
            List<Illegal> illegals = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery().eq(Illegal::getIllegalBehavior, s));
            List<String> list = new ArrayList<>();
            for (Illegal illegal2 : illegals) {
                list.add(illegal2.getIllegalCode());
            }
            //获取违法数量
            Integer wfcount = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .in(IllegalData::getWfxw, list)
                    .between(IllegalData::getWfsj, startTime, endTime));
            map.put("type", s);
            map.put("wfconunt", wfcount);
            mapList.add(map);
        }

        for (String s : dtype) {
            Map map = new HashMap();
            //获取违法代码
            List<Illegal> illegals = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                    .eq(Illegal::getType, s));
            List<String> list = new ArrayList<>();
            for (Illegal illegal2 : illegals) {
                list.add(illegal2.getIllegalCode());
            }
            //获取违法数量
            Integer wfcount = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .in(IllegalData::getWfxw, list)
                    .between(IllegalData::getWfsj, startTime, endTime));
            map.put("type", s);
            map.put("wfconunt", wfcount);
            mapList.add(map);
        }
        return mapList;

    }

    @Override
    public Map InformationReported(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                sectionId = null;
            }
        }
        Map<String, Object> map = new HashMap<>();
        int problemReport = problemMapper.findProblemReport(sectionId, startTime, endTime, null);
        int processed = problemMapper.findProblemReport(sectionId, startTime, endTime, "已解决");
        map.put("problemSum", problemReport);
        map.put("processed", processed);
        map.put("untreated", problemReport - processed);
        return map;
    }

    @Override
    public List<Map> problemReportedType(Integer sectionId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //默认七天
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }

        List<Map> mapList = new ArrayList<>();
        List<Problemtype> problemtypes = problemtypeMapper.selectAllByProblemtype();
        for (Problemtype problemtype : problemtypes) {
            Map map = new HashMap();
            map.put("type", problemtype.getTypes());
            map.put("problemNum", problemMapper.problemReportedType(sectionId, startTime, endTime, problemtype.getId()));
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public List<Map> hourLiveness(Integer sectionId) {

        return null;
    }


}
